<template>
  <div v-if="!loading">
    <Input
      v-model.trim="searchForm.userName"
      search
      enter-button
      placeholder="请输入姓名"
      @on-search="searchValueSet"
      class="search-input"
    >
      <span slot="prepend">姓名:</span>
    </Input>
    <Row>
      <Col span="7" class="border" style="padding:10px; overflow-y: auto;">
        <Tree :data="orgData" @on-select-change="onSelect" :load-data="loadData" />
      </Col>
      <Col span="12" class="border" style="padding:0px; ">
        <InnerPageTable ref="formTable" :config="pageTableConfig"> </InnerPageTable>
      </Col>
      <Col span="5" style="padding:10px;text-align: center;    overflow-y: auto;" class="border">
        <div style="text-align: center;">
          已选择用户：{{ users.length }}个<Button type="text" icon="ios-close" @click="clear">清空</Button>
        </div>
        <Tag v-for="item in users" :key="item.userId" :name="item" closable @on-close="handleClose" type="border">{{
          item.userName
        }}</Tag>
      </Col>
    </Row>
  </div>
</template>

<script>
import mgtApi from '@/api/mgt.js'
import { mapState } from 'vuex'
export default {
  props: {
    orgDatas: { type: Array, default: () => [] }
  },
  computed: {
    ...mapState(['orgList'])
  },
  watch: {
    orgList(newValue, oldValue) {
      this.parseOrgData(newValue)
    }
  },
  data() {
    function formColumns() {
      return [
        {
          title: '姓名',
          width: 140,
          key: 'userName',
          resizable: true
        },
        // {
        //   title: 'LDAP账号',
        //   width: 120,
        //   key: 'userId'
        // },
        {
          title: '组织信息',
          align: 'center',
          render: (h, params) => {
            const orgName = params.row.orgName
              ? params.row.orgName
              : this.flatOrgData.filter(item => item.orgPath === params.row.orgPath)[0]?.orgName
            return h('div', orgName)
          }
        },
        {
          type: 'selection',
          width: 60,
          fixed: 'right',
          align: 'center'
        }
      ]
    }
    return {
      loading: false,
      orgData: [],
      flatOrgData: [],
      searchForm: {
        userName: '',
        userId: '',
        orgName: '',
        orgPath: '',
        pageSize: 10
      },
      GROUP_ORG_NAME: '全集团',
      users: [],
      pageTableConfig: {
        loadDataFn: this.getServiceList,
        columns: formColumns.bind(this)(),
        tableHeight: 500,
        border: true,
        simplePage: true,
        showTotal: false,
        autoMaxHeight: false,
        autoFirst: false, //默认 就是 false, 要配置在这里
        onSelectionChange: this.onSelectionChange
      },
      actions: [
        {
          text: '确定',
          theme: 'primary',
          handle: () => {
            this.$emit('Close', this.users)
          },
          loading: false
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ]
    }
  },
  mounted() {
    if (this.orgList.length <= 0) {
      this.loading = true
      this.$store.dispatch('getOrgList')
    } else {
      this.parseOrgData(this.orgList)
    }
  },
  created() {
    this.$emit('SetTitle', '选择用户')
    this.$emit('SetPageWidth', 1000)
    this.$emit('SetPageMinHeight', 600)
    this.$emit('SetPageActions', this.actions)
  },
  methods: {
    treeToFlat(tree, parentId = null) {
      let flat = []
      for (let node of tree) {
        let copy = { ...node, parentId }
        flat.push(copy)
        if (node.children && node.children.length > 0) {
          flat = flat.concat(this.treeToFlat(node.children, node.id))
        }
      }
      return flat
    },
    parseOrgData(orgDatas) {
      const orgList = orgDatas
      this.orgData = [
        { orgPath: '', orgName: this.GROUP_ORG_NAME, title: this.GROUP_ORG_NAME, expand: true, children: [] }
      ]
      orgList.forEach(element => {
        this.orgData[0].children.push({
          title: element.orgName,
          orgPath: element.orgPath,
          orgName: element.orgName,
          orgData: element,
          children: [],
          loading: false
        })
      })
      this.flatOrgData = this.treeToFlat(this.orgData)
      const { orgPath, orgName } = this.orgData[0]
      this.searchForm.orgPath = orgPath
      this.searchForm.orgName = orgName
      this.loading = false
      this.$nextTick(() => {
        this.searchValueSet()
      })
    },
    uniqueByKey(arr, key) {
      const seen = new Set()
      return arr.filter(item => {
        const serializedKey = JSON.stringify(item[key])
        return seen.has(serializedKey) ? false : seen.add(serializedKey)
      })
    },
    getServiceList(tableObj) {
      let { responseProcess, param } = tableObj
      let { pageNum, pageSize } = param
      // if (this.searchForm.orgPath) {
      // mgtApi
      //   .getUser({
      //     pageNum,
      //     pageSize,
      //     orgCodeParam: this.searchForm.orgPath.replace(/^[^/]+/, ''),
      //     condition: {
      //       userName: this.searchForm.userName,
      //       userId: this.searchForm.userId
      //     }
      //   })
      //   .then(res => {
      //     let { records, pages, total } = res.data
      //     records.forEach(item => {
      //       this.users.findIndex(ele => {
      //         ele.userId === item.userId && (item._checked = true)
      //       })
      //     })
      //     responseProcess(res.data)
      //   })
      // } else {
      mgtApi.getUserListPageNoTotal(param).then(res => {
        let { records, pages, total } = res.data
        records.forEach(item => {
          this.users.findIndex(ele => {
            ele.userId === item.userId && (item._checked = true)
          })
        })
        responseProcess(res.data)
      })
      // }
    },
    onSelectionChange(selection) {
      const objData = this.$refs['formTable'].$children[0].objData
      let unSelectArray = []
      Object.keys(objData).forEach(key => {
        if (!objData[key]._isChecked) {
          unSelectArray.push(objData[key].userId)
        }
      })
      this.users = this.users.concat(selection)
      this.users = this.uniqueByKey(this.users, 'userId')
      this.users = this.users.filter(item => !unSelectArray.includes(item.userId))
    },
    onSelect(node) {
      const name = node[0]?.title
      if (name) {
        if (name === this.GROUP_ORG_NAME) {
          this.searchForm.orgPath = ''
          this.searchForm.orgName = ''
          this.searchValueSet()
        } else {
          this.searchForm.orgPath = node[0]?.orgPath
          this.searchForm.orgName = node[0]?.orgName
          this.searchValueSet()
        }
      }
    },
    searchValueSet() {
      this.$refs['formTable'].load(this.searchForm)
    },
    handleClose(event, user) {
      let index = this.users.indexOf(user)
      if (index > -1) {
        this.users.splice(index, 1)
      }
      let currentPage = this.$refs['formTable'].currentPage
      this.$refs['formTable'].load(this.searchForm, currentPage)
    },
    clear() {
      this.users = []
      let currentPage = this.$refs['formTable'].currentPage
      this.$refs['formTable'].load(this.searchForm, currentPage)
    },
    handleReset() {
      this.searchForm.userName = ''
      this.searchForm.userId = ''
      this.searchValueSet()
    },
    loadData(item, callback) {
      mgtApi.getAuthorizedOrgs(item.orgPath).then(res => {
        const data = []
        if (res.length > 0) {
          res.forEach(element => {
            data.push({
              title: element.orgName,
              orgPath: element.orgPath,
              orgName: element.orgName,
              orgData: element,
              children: [],
              loading: false
            })
          })
          this.flatOrgData = this.treeToFlat(this.orgData)
          callback(data)
        } else {
          callback(data)
          this.searchForm.orgPath = item.orgPath
          this.searchForm.orgName = item.orgName
          this.searchValueSet()
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.self-adaption-wrap {
  /deep/.self-adaption-flex-single {
    margin-bottom: 0;
    padding: 0 5px 10px;
    .search-solt-btn {
      .ivu-form-item-content {
        justify-content: flex-end;
      }
    }
  }
}
.border {
  border: 1px solid #e5e9ee;
  height: 600px;
  padding: 10px;
}
.search-input {
  margin-bottom: 8px;
}

/deep/ .core-modal-body {
  padding: 10px;
}
</style>
